const currentYear = new Date().getFullYear();

const generateYearOptions = (startYear = 1980) => {
  const years = [];
  for (let year = currentYear; year >= startYear; year--) {
    years.push({ category: String(year), airYear: String(year) });
  }
  return [
    { category: '全部', airYear: '' },
    ...years
  ];
};

async function getCachedUsername() {
  try {
    const username = await new Promise((resolve, reject) => {
      wx.getStorage({
        key: 'username',
        success(res) {
          resolve(res.data);
        },
        fail(err) {
          reject(err);
        }
      });
    });

    return username;
  } catch (e) {
    console.warn('缓存读取失败:', e);
    return null;
  }
};

const api = require('../../utils/request.js');
const { searchSubjects, getUserCollections, postUserCollection } = api;

const CATEGORY = {
  MAIN: [
    { 
      id: 0,
      icon: 'wap-nav',
      active: 0,
      originalActive: '动画',
      isActive: true,
      show: false,
      paramKey: 'typeId',
      categories: [
        { category: '动画', typeId: 2 },
        { category: '书籍', typeId: 1 },
        { category: '游戏', typeId: 4 },
        { category: '音乐', typeId: 3 },
        { category: '三次元', typeId: 6 }
      ]
    },
    { 
      id: 1, 
      icon: 'bar-chart-o',
      active: 0, 
      originalActive: '排名',
      isActive: true,
      show: false,
      paramKey: 'sort',
      categories: [
        { category: '排名', sort: 'rank' },
        { category: '收藏', sort: 'heat' },
        { category: '评分', sort: 'score' }
      ]
    },
    { 
      id: 2, 
      icon: 'clock-o',
      active: 0, 
      originalActive: '时间',
      isActive: false,
      show: false,
      paramKey: 'airYear',
      categories: generateYearOptions()
    },
    { 
      id: 3, 
      active: 0, 
      originalActive: '月',
      isActive: false, 
      show: false,
      paramKey: 'airMonth',
      categories: [
        { category: '全部', airMonth: '' },
        { category: '1', airMonth: '1' },
        { category: '2', airMonth: '2' },
        { category: '3', airMonth: '3' },
        { category: '4', airMonth: '4' },
        { category: '5', airMonth: '5' },
        { category: '6', airMonth: '6' },
        { category: '7', airMonth: '7' },
        { category: '8', airMonth: '8' },
        { category: '9', airMonth: '9' },
        { category: '10', airMonth: '10' },
        { category: '11', airMonth: '11' },
        { category: '12', airMonth: '12' }
      ]
    },
    { 
      id: 4, 
      icon: 'label-o', 
      active: 0, 
      originalActive: '标签',
      isActive: false, 
      show: false,
      paramKey: 'metaTag',
      categories: [
        { category: '全部', metaTag: [] },
        { category: '科幻', metaTag: ['科幻'] },
        { category: '喜剧', metaTag: ['喜剧'] },
        { category: '百合', metaTag: ['百合'] },
        { category: '校园', metaTag: ['校园'] },
        { category: '惊悚', metaTag: ['惊悚'] },
        { category: '后宫', metaTag: ['后宫'] },
        { category: '悬疑', metaTag: ['悬疑'] },
        { category: '恋爱', metaTag: ['恋爱'] },
        { category: '奇幻', metaTag: ['奇幻'] },
        { category: '推理', metaTag: ['推理'] },
        { category: '运动', metaTag: ['运动'] },
        { category: '音乐', metaTag: ['音乐'] },
        { category: '冒险', metaTag: ['冒险'] },
        { category: '穿越', metaTag: ['穿越'] },
        { category: '玄幻', metaTag: ['玄幻'] },
        { category: '历史', metaTag: ['历史'] },
        { category: '日常', metaTag: ['日常'] },
        { category: '美食', metaTag: ['美食'] },
        { category: '萌系', metaTag: ['萌系'] },
        { category: '战斗', metaTag: ['战斗'] },
        { category: '机战', metaTag: ['机战'] },
        { category: '剧情', metaTag: ['剧情'] },
        { category: '恐怖', metaTag: ['恐怖'] },
        { category: '武侠', metaTag: ['武侠'] }
      ]
    },
  ]
};

Page({
  data: {
    mainCategories: CATEGORY.MAIN,
    showMonth: false,
    showTag: true,
    showPopup: false,
    rankList: [],
    currentPage: '1',
    pageSize: 20,
    total: 0,
    maxPage: 1
  },

  onLoad(options) {
    this.setData({
      showMonth: this.shouldShowMonthCategory(),
      showTag: this.shouldShowTagCategory()
    });
  },

  onReady() {

  },

  onShow() {
    this.fetchRankData();
  },

  onHide() {

  },

  onUnload() {

  },

  onPullDownRefresh() {

  },

  onReachBottom() {

  },

  onShareAppMessage() {

  },

  /**
   * @example
   * // 返回值示例
   * {
   *  typeId: 4,
   *  sort: 'heat',  
   *  airYear: '2023',
   *  airMonth: '',
   *  metaTag: []
   * }
   */
  getSelectedParams() {
    const { mainCategories } = this.data;
  
    return mainCategories.reduce((params, item) => {
      if (item.isActive && item.categories[item.active]) {
        const selected = item.categories[item.active];
        const paramKey = item.paramKey;
  
        if (paramKey in selected) {
          params[paramKey] = selected[paramKey];
        }
      }
      return params;
    }, {});
  },

  buildRequestBody(selectedParams) {
    const body = {
      keyword: '',
      sort: 'match',
      filter: {}
    };
  
    Object.keys(selectedParams).forEach(key => {
      const value = selectedParams[key];
  
      switch (key) {
        case 'typeId':
          body.filter.type = [value];
          break;
        case 'sort':
          const sortMap = {
            rank: 'rank',
            heat: 'heat',
            score: 'score'
          };
          body.sort = sortMap[value] || 'match';
          break;
        case 'airYear':
          if (value) {
            const year = value;
            const airDateStart = `${year}-01-01`;
            const airDateEnd = `${year}-12-31`;
            body.filter.air_date = [`>=${airDateStart}`, `<=${airDateEnd}`];
          }
          break;
        case 'airMonth':
          if (value) {
            const timeCategory = this.data.mainCategories.find(c => c.id === 2);
            const year = timeCategory?.categories[timeCategory.active]?.airYear;
  
            if (year) {
              const dateStr = `${year}-${value.padStart(2, '0')}-01`;
              const nextMonth = parseInt(value) + 1;
              const nextYear = nextMonth > 12 ? parseInt(year) + 1 : year;
              const nextMonthStr = (nextMonth % 12 || 12).toString().padStart(2, '0');
              const airDateEnd = `${nextYear}-${nextMonthStr}-01`;
  
              body.filter.air_date = [`>=${dateStr}`, `<${airDateEnd}`];
            }
          }
          break;
        case 'metaTag':
          if (Array.isArray(value) && value.length > 0) {
            body.filter.meta_tags = value;
          }
          break;
      };
    });

    body.filter.rating = ['>=4.3', '<9.5'];
    body.filter.rank = ['>0'];
  
    return body;
  },

  async fetchUserCollections(selectedParams) {
    const { typeId } = selectedParams;
    const username = await getCachedUsername();

    try {
      const collectionsRes = await getUserCollections(username, typeId);

      const collectionMap = {};
      collectionsRes.data.forEach(collection => {
        const subject = collection.subject;
        collectionMap[subject.id] = {
          collected: true,
          rate: collection.rate,
          type: collection.type,
          comment: collection.comment,
          tags: collection.tags,
          private: collection.private,
          updatedAt: collection.updated_at
        };
      });

      return collectionMap;
    } catch (err) {
      console.error('获取用户收藏失败:', err);
      return {};
    }
  },

  async fetchRankData(page = 1, pageSize = this.data.pageSize) {
    const selectedParams = this.getSelectedParams();
    const body = this.buildRequestBody(selectedParams);
  
    try {
      const offset = (page - 1) * pageSize;

      const res = await searchSubjects(pageSize, offset, body);
      let rankList = res.data || [];

      const total = res.total || 0;
      const maxPage = Math.ceil(total / this.data.pageSize);

      const collectionMap = await this.fetchUserCollections(selectedParams);

      rankList = rankList.map(item => {
        const collection = collectionMap[item.id] || {};
  
        return {
          ...item,
          collected: !!collection.collected,
          userRate: collection.rate,
          userType: collection.type,
          userComment: collection.comment,
          userTags: collection.tags,
          isPrivate: collection.private,
          updatedAt: collection.updatedAt,
          infoItems: this.formatInfoItems(item)
        };
      });
  
      this.setData({
        rankList,
        currentPage: String(page),
        total,
        maxPage
      });
    } catch (err) {
      console.error('请求失败:', err);
      this.setData({ rankList: [] });
    }
  },

  categoryTap(e) {
    const clickedId = parseInt(e.currentTarget.dataset.id);
    const { mainCategories } = this.data;
    
    const updatedCategories = mainCategories.map(item => {
      if (item.id === clickedId) {
        return {
          ...item,
          show: !item.show
        };
      } else {
        return {
          ...item,
          show: false
        };
      }
    });
    
    this.setData({ mainCategories: updatedCategories });
  },

  categoriesItemTap(e) {
    const idx = parseInt(e.currentTarget.dataset.id); // 子分类项索引
    const categoryId = parseInt(e.currentTarget.dataset.categoryid); // 主分类id
    let shouldFetch = true;
  
    const mainCategories = this.data.mainCategories.map(item => {
      if (item.id === categoryId) {
        // 子分类项无变化
        if (idx === item.active) {
          shouldFetch = false;
          return {
            ...item,
            show: false
          }
        }
  
        // 子分类项变化：索引为零 && 子分类项为“全部”
        if (idx === 0 && item.categories[idx].category === '全部') {
          shouldFetch = true;
          return {
            ...item,
            active: idx,
            isActive: false,
            show: false
          };
        }

        // 子分类项变化：其他情况
        shouldFetch = true;
        return {
          ...item,
          active: idx,
          isActive: true,
          show: false
        };
      }

      return item;
    });
  
    this.setData({ mainCategories }, () => {
      this.setData({ 
        showMonth: this.shouldShowMonthCategory(),
        showTag: this.shouldShowTagCategory()
      });
      if (shouldFetch) this.fetchRankData();
    });
  },

  containerTap(e) {
    const dataset = e.target.dataset;
    
    if (dataset.id !== undefined || dataset.categoryid !== undefined) {
      return;
    }
  
    const mainCategories = this.data.mainCategories.map(item => ({
      ...item,
      show: false
    }));
  
    this.setData({ mainCategories });
  },

  onCardClick({ detail }) {
    const { itemData } = detail;
    console.log(itemData);
    wx.navigateTo({
      url: `/pages/item-detail/item-detail?id=${itemData.id}`
    });
  },

  onCardCollect({ detail }) {
    const { itemData } = detail;
    this.setData({ 
      itemData,
      itemId: itemData.id,
      showPopup: true,
    });
  },

  onPopupClose() {
    this.setData({ 
      showPopup: false
    });
  },

  async onPopupSubmit({ detail }) {
    const { formData } = detail;
    const body = {
      type: formData.collection.number,
      rate: formData.ratingScore,
      comment: formData.roast,
      private: formData.isPrivate
    }

    try {
      await postUserCollection(this.data.itemId, body);

      this.setData({ showPopup: false })
      this.fetchRankData(this.data.currentPage);
    } catch (err) {
      console.warn('更新失败:', err);
    }
  },

  toPrev() {
    const page = parseInt(this.data.currentPage);
    if (page > 1) {
      this.fetchRankData(page - 1);
    }
  },

  toNext() {
    const page = parseInt(this.data.currentPage);
    const maxPage = this.data.maxPage;
    
    if (page < maxPage) {
      this.fetchRankData(page + 1);
    }
  },

  // 工具方法
  // 无具体年份时不可选择月份
  shouldShowMonthCategory() {
    const timeCategory = this.data.mainCategories.find(item => item.id === 2);
    return timeCategory && timeCategory.active !== 0;
  },
  // 游戏和音乐分类下不可选择标签
  shouldShowTagCategory() {
    const typeCategory = this.data.mainCategories.find(item => item.id === 0);
    return typeCategory && typeCategory.active !== 2 && typeCategory.active !== 3;
  },

  formatInfoItems(subject) {
    const items = [];
  
    if (subject.date) {
      const [year, month, day] = subject.date.split('-');
      items.push(`${year}年${month}月${day}日`);
    }
  
    // 动画 eps
    if (subject.eps && subject.type === 2) {
      items.push(`${subject.eps}话`);
    }
  
    // 书籍 vol
    if (subject.volumes && subject.type === 1) {
      items.push(`${subject.volumes}册`);
    }
  
    if (subject.platform) {
      items.push(`${subject.platform}`);
    }
  
    if (Array.isArray(subject.infobox)) {
      const infoboxKeys = ['作者', '原作', '导演', '角色设计', '编剧', '画师'];
      subject.infobox.forEach(item => {
        if (infoboxKeys.includes(item.key) && item.value && typeof item.value === 'string') {
          items.push(`${item.key}: ${item.value}`);
        }
      });
    }
  
    return items;
  }
})